#include "button.h"

Button::Button(std::string id, int x, int y, int size_x, int size_y, std::function<void()> action,
		std::string graphic_up, std::string graphic_down,
		ALLEGRO_FONT* label_font, std::string label, const unsigned char label_color[3])
	: GuiElement(id, x, y, size_x, size_y)
{
	m_graphic_up = graphic_up;
	m_graphic_down = graphic_down;
	m_action = action;
	m_label_font = label_font;
	m_label = label;
	m_label_color = al_map_rgb(label_color[0], label_color[1], label_color[2]);

	m_down = false;
}

Button::~Button()
{
	al_destroy_font(m_label_font);
}

void Button::PrimaryMouseButtonUp(int x, int y)
{
	// Did we release the mouse button down on the button?
	bool hit = false;
	if (x >= m_x && x < m_x + m_size_x && y >= m_y && y < m_y + m_size_y)
		hit = true;

	// If we have clicked it before, trigger the action. If not, don't do it.
	if (m_down && hit)
	{
		// TODO: Error handling if action has not been set.
		m_action();
		m_down = false;
	}
	else
	{
		m_down = false;
	}
}

void Button::PrimaryMouseButtonDown(int x, int y)
{
	// Did we press the mouse button down on the button?
	bool hit = false;
	if (x >= m_x && x < m_x + m_size_x && y >= m_y && y < m_y + m_size_y)
		hit = true;

	// If yes, it is not pressed. If not, it is not.
	if (hit)
		m_down = true;
	else
		m_down = false;
}

void Button::Draw()
{
	if (m_down)
	{
		ALLEGRO_BITMAP* graphic = allegro_bitmap_resource_manager.GetResource(m_graphic_down);
		al_draw_scaled_bitmap(graphic, 0, 0, al_get_bitmap_width(graphic), al_get_bitmap_height(graphic),
			m_x, m_y, m_size_x, m_size_y, NULL);
	}
	else
	{
		ALLEGRO_BITMAP* graphic = allegro_bitmap_resource_manager.GetResource(m_graphic_up);
		al_draw_scaled_bitmap(graphic, 0, 0, al_get_bitmap_width(graphic), al_get_bitmap_height(graphic),
			m_x, m_y, m_size_x, m_size_y, NULL);
	}

	if (m_label != "")
	{
		al_draw_text(m_label_font, m_label_color, m_x + m_size_x / 2,
			m_y + m_size_y / 2 - al_get_font_line_height(m_label_font) / 2, ALLEGRO_ALIGN_CENTRE, m_label.c_str());
	}
}